package edu.sdufe.controller;

import edu.sdufe.pojo.Condition;
import edu.sdufe.pojo.Student;
import edu.sdufe.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    // 查询所有学生
    @GetMapping
    public List<Student> getAllStudents() {
        return studentService.queryAllStudents();
    }

    // 根据条件查询学生
    @GetMapping("/search")
    public List<Student> getStudentsByCondition(Condition condition) {
        System.out.println(condition);
        return studentService.queryStudentsByCondition(condition);
    }

    // 新增单个学生
    @PostMapping
    public int addStudent(@RequestBody Student student) {
        int result = studentService.addStudent(student);
        if (result > 0) {
            studentService.updateRanksByScore();
        }
        return result;
    }

    // 更新学生信息
    @PutMapping
    public int updateStudent(@RequestBody Student student) {
        int result = studentService.updateStudent(student);
        if (result > 0) {
            studentService.updateRanksByScore();
        }
        return result;
    }
    // 更新学生排名
    @PutMapping("/rank/{id}/{newRank}")
    public int updateStudentRank(
            @PathVariable Integer id,        // 从路径中获取id
            @PathVariable Integer newRank    // 从路径中获取newRank
    ) {
        return studentService.updateStudentRank(id, newRank);
    }

    // 删除学生
    @DeleteMapping("/{id}")
    public int deleteStudent(@PathVariable Integer id) {
        int result = studentService.deleteStudent(id);
        if ( result > 0) {
            studentService.updateRanksByScore();
        }
        return result;
    }

    // 获取排名范围内的学生
    @GetMapping("/rank/{min}/{max}")
    public List<Student> getStudentsByRankRange(@PathVariable Integer min, @PathVariable Integer max) {
        return studentService.queryStudentsByRankRange(min, max);
    }
    // 新增：自动根据总分更新所有学生排名
    @PutMapping("/updateRanksByScore")
    public String updateRanksByScore() {
        studentService.updateRanksByScore();
        return "排名更新成功";
    }

}
